library(quantmod)
library(psych)
library(rugarch)

sp500 <- new.env()

prepShares<-function(s)
{
  s = Cl(s)
  return (dailyReturn(s))
}

getSymbols("MSFT",src='yahoo',
           from = as.Date("2017-01-04"), to = as.Date("2019-12-25"))
getSymbols("AMZN",src='yahoo',
           from = as.Date("2017-01-04"), to = as.Date("2019-12-25"))

# 计算收益
MSFTprofit = prepShares(MSFT)
AMANprofit = prepShares(AMZN)

# 标准化
MSFTstProfit = scale(MSFTprofit,scale=T)
AMANstProfit = scale(AMANprofit,scale=T)

# 相关性
m = cbind(MSFTprofit, AMANprofit)
msftamzncor=corr.test(as.data.frame(m))
print("msftamzncor")
print(msftamzncor)
# s1 <- var(MSFTprofit)
# s2 <- var(AMANprofit)
# s12 = cov(MSFTprofit, AMANprofit)
# p = s12/(s1*s2)

# GARCH
getGARCH<-function(data)
{
  garchspec = ugarchspec(variance.model = list(model="sGARCH",  
                                               garchOrder=c(1,1)), mean.model = list(armaOrder=c(0,0)))
  fitResult = ugarchfit(spec=garchspec, data=data, cond.dist="t")
  r = fitResult@fit$residuals
  return (list(fitResult,r))
}

lagCov<-function(a,b=NULL,isList=T)
{
  if(is.null(b))
  {
    b=a
  }
  if(isList)
  {
    a<-as.vector(unlist(a[1]))
    b<-as.vector(unlist(b[1]))
  }
  else
  {
    a<-as.vector(a)
    b<-as.vector(b)
  }
  l<-length(a)
  result<-c()
  i=2
  j=1
  for(i in 2:(l-1))
  {
    s1<-c()
    s2<-c()
    for(j in 1:i)
    {
      s1[j]=a[j]
      s2[j]=b[l-(j-1)]
    }
    s2=rev(s2)
    result[i]=cov(s1,s2)
  }
  return(result)
}

MSFTg=getGARCH(MSFTprofit)
AMANg=getGARCH(AMANprofit)
cov1=lagCov(MSFTg[2])
cov2=lagCov(AMANg[2])
plot(cov1,type = "l")
plot(cov2,type = "l")
print("GARCH Cov Finished")

# q6
s1=lagCov(MSFTprofit,NULL,F)
s2=lagCov(AMANprofit,NULL,F)
s12=lagCov(MSFTprofit,AMANprofit,F)

caluW1<-function(s1,s2,s12) # 优化计算单个w1
{
  obj <- function(w)
  {
    .w=1-w
    sp = w^2*s1^2+.w^2*s2^2+2*w*.w*s12
    return(sp)
  }
  w1=optimize(obj,lower=0,upper=1)$minimum
  return (w1)
}

allW1=c()
for(i in 1:length(s1)) # 计算所有w1
{
  allW1[i]=caluW1(s1[i],s2[i],s12[i])
}
plot(allW1,type = "l")
print("MSFT w Finished")

# q7
getSymbols("^GSPC",src='yahoo',
           from = as.Date("2017-01-04"), to = as.Date("2019-12-25"))
getSymbols("MSFT",src='yahoo',
           from = as.Date("2017-01-04"), to = as.Date("2019-12-25"))
GSPCprofit = prepShares(GSPC)
MSFTprofit = prepShares(MSFT)
CAPMbeta<-function(sh1,sh2)
{
  s12 = lagCov(sh1, sh2, F)
  s2 = lagCov(sh2, NULL, F)
  return (s12/s2)
}
beta = CAPMbeta(MSFTprofit, GSPCprofit)
plot(beta,type = "l")
print("MSFT beta Finished")
